package com.zyx.xunyilu.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zyx.xunyilu.config.jwt.JWTUtils;
import com.zyx.xunyilu.entity.Article;
import com.zyx.xunyilu.entity.User;
import com.zyx.xunyilu.enums.ReleaseEnum;
import com.zyx.xunyilu.mapper.ArticleMapper;
import com.zyx.xunyilu.service.UserService;
import com.zyx.xunyilu.utils.RestResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * 文章API
 * @ClassName: ArticleController
 * @author: zyx
 * @E-mail: 1377631190@qq.com
 * @DATE: 2019/11/28 20:11
 */
@CrossOrigin
@Slf4j
@RestController
@RequestMapping("/article")
public class ArticleController {

    private UserService userService;
    private JWTUtils    jwtUtils;
    private ArticleMapper   articleMapper;

    @Autowired
    public ArticleController(UserService userService, JWTUtils jwtUtils, ArticleMapper articleMapper) {
        this.userService = userService;
        this.jwtUtils = jwtUtils;
        this.articleMapper = articleMapper;
    }

    @RequiresRoles("admin")
    @PostMapping("/authorize/{id}")
    public RestResponse authorize(@PathVariable("id") Integer id,
                                  @RequestParam("flag") ReleaseEnum flag) {
        Article article = new Article().setId(id).setFlag(flag);
        int i = articleMapper.updateById(article);
        if (i > 0) {
            return RestResponse.ok();
        } else {
            return RestResponse.fail();
        }
    }

    @RequiresRoles("admin")
    @PostMapping("/authorize/more")
    public RestResponse authorizeMore(@RequestParam("ids[]") List<Integer> ids,
                                      @RequestParam("flag") ReleaseEnum flag) {
        ids.forEach(t -> {
            Article article = new Article().setId(t).setFlag(flag);
            articleMapper.updateById(article);
        });
        return RestResponse.ok();
    }

    @RequiresRoles("admin")
    @PostMapping("/delete/{id}")
    public RestResponse delete(@PathVariable("id") Integer id) {
        int i = articleMapper.deleteById(id);
        if (i > 0) {
            return RestResponse.ok();
        } else {
            return RestResponse.fail();
        }
    }

    @RequiresRoles("admin")
    @PostMapping("/delete/more")
    public RestResponse deleteMore(@RequestParam("ids[]") List<Integer> ids) {
        ids.forEach(t -> {
            articleMapper.deleteById(t);
        });
        return RestResponse.ok();
    }


    @GetMapping("/get/{id}")
    public RestResponse getArticleById(@PathVariable("id") Integer id) {
        Article article = articleMapper.selectById(id);
        return RestResponse.ok(article);
    }

    @GetMapping("/page")
    public RestResponse articlePage(@RequestParam(value = "page", defaultValue = "1") Integer page,
                                    @RequestParam(value = "size", defaultValue = "15") Integer size,
                                    Article article,
                                    @RequestParam(value = "checkTime", required = false) String time) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Article::getId);
        if (article.getTitle() != null) {
            queryWrapper.like(Article::getTitle, article.getTitle());
        }
        if (article.getContent() != null) {
            queryWrapper.like(Article::getContent, article.getContent());
        }
        if (time != null && !"".equals(time)) {
            String[] split = time.split(" - ");
            if (split.length > 1) {
                queryWrapper.between(Article::getTime, split[0], split[1]);
            }
        }
        IPage<Article> articleIPage = articleMapper.selectPage(new Page<>(page, size),
                queryWrapper);
        if (articleIPage == null) {
            return RestResponse.fail("没有数据!");
        }
        return RestResponse.ok(articleIPage);
    }

    @PostMapping("/add")
    public RestResponse add(@RequestParam("title") String title,
                            @RequestParam("content") String content,
                            @RequestParam("time") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm") Date time,
                            @RequestAttribute("token") String token) throws Exception {
        if (StringUtils.isEmpty(content)) {
            throw new Exception("内容不能为空哦!");
        }
        if (new Date().before(time)) {
            throw new Exception("时间错误!");
        }
        String username = jwtUtils.getUsername(token);
        User userByName = userService.findUserByName(username).clearUser();
        Article article = new Article(null, userByName.getId(), title, content, 0, ReleaseEnum.NO_CHECK, time, null);
        int insert = articleMapper.insert(article);
        if (insert > 0) {
            Article result = articleMapper.selectById(article.getId());
            return RestResponse.ok(result);
        }
        log.error("{} -添加文章失败!", userByName);
        return RestResponse.fail("添加失败");
    }

}

